

import java.io.IOException;

import java.sql.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Messages
 */
@WebServlet("/Messages")
public class Messages extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public Messages() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession ses = request.getSession();
		Integer USER_ID = (Integer) ses.getAttribute("USER_ID");
		Integer P_ADDRESS = (Integer) ses.getAttribute("P_ADDRESS");
		
		if(USER_ID==null||P_ADDRESS==null){
			response.sendRedirect("Overview");
			return;
		}
		
		Database baza = null;
		ResultSet rs = null;
		
		request.getRequestDispatcher("Messages.jsp").forward(request, response);
		
		
	}

	public static void create_message(int recipientID, String Message) throws SQLException{
		Database baza = new Database();
		PreparedStatement ps = baza.Exec("CREATE_NEW_MESSAGE",	recipientID + ", ?").SafeInput();
		ps.setString(1, Message);
		ps.execute();
		ps.close();
		baza.Close();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession ses = request.getSession();
		Integer USER_ID = (Integer) ses.getAttribute("USER_ID");
		Integer P_ADDRESS = (Integer) ses.getAttribute("P_ADDRESS");
		
		if(USER_ID==null||P_ADDRESS==null){
			response.sendRedirect("Overview");
			return;
		}
		Database baza = null;
		ResultSet rs = null;
		String recipient = request.getParameter("recipient");
		String message = request.getParameter("message");
		
		if(recipient == null||message == null||recipient=="" || message == ""){
			response.sendRedirect("Messages");
		} else {
			try {
				baza = new Database();
				PreparedStatement pr_email = baza.Select("USER_ID").From("G_USER").Where("EMAIL = ?").SafeInput();
				pr_email.setString(1, recipient);
				rs = pr_email.executeQuery();
				
				if(rs.isBeforeFirst()){
					rs.next();
					Integer uid = rs.getInt("USER_ID");
					create_message(uid, message);
					response.sendRedirect("Messages");
				} else {
					response.sendRedirect("Messages");
				}
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		
	}

}
